var GODSON_OF_SINA = function () {
	var that = this;
	this.appName = "新浪微博助手";
	this.author = "GodSon";
	this.version = chrome.app.getDetails().version;
	this.client_id = "41484100";
	this.client_secret = "f4b87d74f7d7cc780a833da179efeb43";
	this.sinaAdpt = new OAuth2('sina', {
			client_id : that.client_id,
			client_secret : that.client_secret,
			api_scope : ''
		});
	
	this.query_time = 30000;
	this.interval = null;
	this.send = false;
	this.tolong = false;
	this.file = null;
	this.img = null;
};

GODSON_OF_SINA.prototype.authorize = function () {
	this.sinaAdpt.authorize(this.initCallBack);
};

GODSON_OF_SINA.prototype.initCallBack = function () {
	var that = SINA;
	that.accessToken = that.sinaAdpt.getAccessToken();
	that.gets(APIV.account.get_uid, {
		access_token : that.sinaAdpt.getAccessToken()
	}, function (resp) {
		that.getUserInfo(resp.uid, that.initBaseInfo);
	});
	that.interval = setInterval(that.checkUpdates, that.query_time);
};

GODSON_OF_SINA.prototype.getUserInfo = function (uid, callback) {
	var that = this;
	that.gets(APIV.users.show, {
		uid : uid
	}, function (resp) {
		if (callback)
			callback.call(SINA, resp);
	});
};

GODSON_OF_SINA.prototype.initBaseInfo = function (userInfo) {
	this.set('uid', userInfo.id);
	this.set('screenname', userInfo.screen_name);
	this.set('verified', userInfo.verified);
	this.set('imageurl', userInfo.profile_image_url);
	this.set('desc', userInfo.description);
	
	this.showFirstTimeNotification();
	this.getEmotions();
	this.getFrendCount();
};

GODSON_OF_SINA.prototype.getEmotions = function () {
	var that = this;
	that.gets(APIV.other.emotions, {}, function (resp) {
		var rplFace = {};
		$.each(resp, function (i, v) {
			rplFace[v.phrase] = '<img src="' + v.url + '"/>';
		});
		that.set("emotions_tpl", that.jsonTostr(rplFace));
	});
};

GODSON_OF_SINA.prototype.getFrendCount = function () {
	var that = this;
	var friends = [];
	
	var friends_count = that.get('friends_count');
	var friendsHis = that.get('friends') ? JSON.parse(that.get('friends')) : false;
	if (!friends_count || !(friendsHis && friendsHis.length > 0)) {
		DownFreindShip(0);
		return;
	}
	
	that.gets(APIV.users.show, {
		uid : that.get('uid')
	}, function (resp) {
		var newCount = resp.friends_count;
		if (friends_count != newCount) {
			that.set('friends_count', newCount);
			DownFreindShip(0);
		}
	});
	
	function DownFreindShip(cursor) {
		that.gets(APIV.friendships.friends, {
			'count' : 200,
			uid : that.get('uid'),
			'cursor' : cursor
		}, function (response) {
			friends.push({
				name : "_夏悸",
				py : "godson",
				pysx : 'xj'
			});
			for (var i = 0; i < response.users.length; i++) {
				if (response.users[i].name == "_夏悸")
					continue;
				var user = {};
				user['name'] = response.users[i].name;
				user['py'] = CC2PY(response.users[i].name).toLocaleLowerCase();
				user['pysx'] = CC2PYF(response.users[i].name).toLocaleLowerCase();
				friends.push(user);
			}
			if (response.next_cursor != 0 && response.next_cursor != cursor) {
				DownFreindShip(response.next_cursor);
			} else {
				that.set('friends', that.jsonTostr(friends));
				friends = [];
			}
		});
	}
};

GODSON_OF_SINA.prototype.showFirstTimeNotification = function () {
	var notification = webkitNotifications.createNotification('../icon48.png', "新浪微博助手", this.get('screenname') + "\n欢迎使用GodSon分享新浪微博助手!");
	notification.show();
	if (confirm("关注官方微博,获取最新更新信息.")) {
		this.attentionme();
	}
	this.send_status("#GodSon分享# 我正在使用Chrome插件--新浪微博助手。https://chrome.google.com/webstore/detail/bebkcfflfplfpjoebbabeejckmjagafh", null, null);
};

GODSON_OF_SINA.prototype.checkUpdates = function () {
	var that = SINA;
	if (!that.sinaAdpt.getAccessToken()) {
		return;
	}
	
	var text = {
		"status" : "新微博未读数",
		"follower" : "新粉丝数",
		"cmt" : "新评论数",
		"dm" : "新私信数",
		"mention_status" : "新提及我的微博数",
		"mention_cmt" : "新提及我的评论数",
		"group" : "微群消息未读数",
		"notice" : "新通知未读数",
		"invite" : "新邀请未读数",
		"badge" : "新勋章数",
		"photo" : "相册消息未读数"
	};
	that.gets(APIV.remind.unread_count2, {
		access_token : that.sinaAdpt.getAccessToken()
	}, function (resp) {
		var content = "",
		count = 0;
		var longSetting = JSON.parse(that.get("longSetting"));
		for (var key in text) {
			if (resp[key] && longSetting[key]) {
				content += text[key] + ":" + resp[key] + "\r\n";
				count += resp[key];
				that.set(key, resp[key]);
			}
		}
		that.set('unread_count', count);
		if (count) {
			that.setIconInfo(count + "", content);
			if ((longSetting.tips && longSetting.tips == "true") && (parseInt(that.get("cmt")) > 0 || parseInt(that.get("mention_cmt")) > 0 || parseInt(that.get("mention_status")) > 0)) {
				var n = that.showMsgNotification(content);
				n.onclick = function () {
					chrome.tabs.query({
						title : "信息阅读 - GodSon分享"
					}, function (tabs) {
						if (tabs.length > 0) {
							chrome.tabs.reload(tabs[0].id);
						} else {
							chrome.tabs.create({
								"url" : "weibo.html",
								"index" : 0
							});
						}
						if (resp.dm > 0) {
							chrome.tabs.create({
								"url" : "http://www.weibo.com/messages",
								"index" : 1
							});
						}
					});
				};
			}
		} else {
			that.setIconInfo("", that.appName);
		}
	});
};

GODSON_OF_SINA.prototype.jsonTostr = function (o) {
	return JSON.stringify(o);
};

GODSON_OF_SINA.prototype.setIconInfo = function (content, title) {
	chrome.browserAction.setTitle({
		title : title
	});
	chrome.browserAction.setBadgeBackgroundColor({
		color : [0, 0, 0, 255]
	});
	chrome.browserAction.setBadgeText({
		text : content
	});
};

GODSON_OF_SINA.prototype.showMsgNotification = function (msg) {
	var notification = webkitNotifications.createNotification('../icon48.png', "GodSon分享提醒", msg);
	notification.replaceId = "GodSon";
	notification.show();
	return notification;
};

GODSON_OF_SINA.prototype.set = function (key, value) {
	this.sinaAdpt.set(key, value);
};

GODSON_OF_SINA.prototype.get = function (key) {
	return this.sinaAdpt.get(key);
};

/**
 * 关注开发者
 */
GODSON_OF_SINA.prototype.attentionme = function () {
	var that = this;
	if ("1721282520" == that.get('uid'))
		return true;
	if (that.get('Isfriendships'))
		return true;
	
	that.post(APIV.friendships.create, {
		uid : "1721282520"
	}, function () {
		that.set('Isfriendships', true);
	});
};

/**
 * 清空各种提醒
 */
GODSON_OF_SINA.prototype.clearCounts = function (flag) {
	var that = this;
	var longSetting = JSON.parse(that.get("longSetting"));
	var flags = flag || ['mention_status', 'follower', 'mention_cmt', 'cmt'];
	that.set('unread_count', 0);
	for (var idx in flags) {
		if (that.get(flags[idx]) && longSetting[flags[idx]] == "true") {
			var request = {
				'type' : flags[idx]
			};
			that.post(APIV.remind.set_count, request, function callback(rsp) {});
		}
		that.set(flags[idx], 0);
	}
	that.setIconInfo("", that.appName);
};

/**
 * 计算时间差
 */
GODSON_OF_SINA.prototype.dateDiff = function (timestamp) {
	var now = new Date();
	var diff = Math.floor(now.getTime() / 1000) - Math.floor((timestamp / 1000));
	
	if (diff < 0) {
		return "刚刚";
	} else if (diff < 60) {
		return diff + "秒前";
	} else if (diff < 3600) {
		return Math.ceil(diff / 60) + "分钟前";
	}
	
	var date = new Date(timestamp);
	
	if (date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth() && date.getDate() === now.getDate()) {
		return formatTime(date, "今天 HH:MS");
	}
	if (date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth() && date.getDate() === now.getDate() - 1) {
		return formatTime(date, "昨天 HH:MS");
	}
	
	return formatTime(date, "MM月DD日 HH:MS");
	
	function formatTime(d, f) {
		if (d == null) {
			return "";
		}
		
		f = f.replace(/YYYY/g, d.getFullYear());
		f = f.replace(/MM/g, addZero((d.getMonth() + 1)));
		f = f.replace(/DD/g, addZero(d.getDate()));
		f = f.replace(/HH/g, addZero(d.getHours()));
		f = f.replace(/MS/g, addZero(d.getMinutes()));
		f = f.replace(/SS/g, addZero(d.getSeconds()));
		
		return f;
	}
	
	function addZero(a) {
		if (a <= 9 && a >= 0) {
			return "0" + a;
			
		} else {
			return a;
		}
	}
};

GODSON_OF_SINA.prototype.post = function (url, params, callback, errorCallback) {
	var that = this;
	params = $.extend({}, params, {
			access_token : that.sinaAdpt.getAccessToken()
		});
	$.ajax({
		url : url,
		type : "POST",
		data : params,
		dataType : "json",
		cache : false,
		success : function (data, textStatus, jqXHR) {
			if (data) {
				if (textStatus != "success") {
					that.showMsgNotification("操作失败！请重试！");
					return;
				}
				
				if (data.error) {
					that.set("error_msg", data.error_code);
					if (data.error_code == "21315") {
						that.sinaAdpt.clear("accessToken");
						that.sinaAdpt.authorize(that.initCallBack);
						return;
					}
					that.showMsgNotification("操作失败！" + data.error_code + ":" + data.error);
					return;
				}
				
				callback.call(that, data);
			} else {
				that.set("error_msg", jqXHR.status);
			}
		},
		error : function (jqXHR, textStatus, errorThrown) {
			if (textStatus != "error" && jqXHR.responseText) {
				var data = JSON.parse(jqXHR.responseText);
				if (errorCallback) {
					errorCallback.call(jqXHR, textStatus);
				} else {
					that.set("error_msg", data.error_code);
					if (data.error_code == "21315") {
						that.sinaAdpt.clear("accessToken");
						that.sinaAdpt.authorize(that.initCallBack);
						return;
					}
					that.showMsgNotification("操作失败！" + data.error_code + ":" + data.error);
				}
			} else {
				that.set("error_msg", "操作失败！请重试！");
			}
		}
	});
};

GODSON_OF_SINA.prototype.gets = function (url, params, callback, errorCallback) {
	var that = this;
	params = $.extend({}, params, {
			access_token : that.sinaAdpt.getAccessToken()
		});
	$.ajax({
		url : url,
		type : "GET",
		data : params,
		cache : false,
		dataType : "json",
		success : function (data, textStatus, jqXHR) {
			if (data) {
				if (textStatus != "success") {
					that.showMsgNotification("操作失败！请重试！");
					return;
				}
				
				if (data.error) {
					that.set("error_msg", data.error_code);
					if (data.error_code == "21315") {
						that.sinaAdpt.clear("accessToken");
						that.sinaAdpt.authorize(that.initCallBack);
						return;
					}
					that.showMsgNotification("操作失败！" + data.error_code + ":" + data.error);
					return;
				}
				
				if (callback)
					callback.call(that, data);
			} else {
				that.set("error_msg", jqXHR.status);
			}
		},
		error : function (jqXHR, textStatus, errorThrown) {
			if (textStatus != "error" && jqXHR.responseText) {
				var data = JSON.parse(jqXHR.responseText);
				if (errorCallback) {
					errorCallback.call(jqXHR, textStatus);
				} else {
					that.set("error_msg", data.error_code);
					if (data.error_code == "21315") {
						that.sinaAdpt.clear("accessToken");
						that.sinaAdpt.authorize(that.initCallBack);
						return;
					}
					that.showMsgNotification("操作失败！" + data.error_code + ":" + data.error);
				}
			} else {
				that.set("error_msg", "操作失败，请重试！");
			}
		}
	});
};

GODSON_OF_SINA.prototype.getQueryString = function (sUrl) {
	var array;
	
	var index = sUrl.indexOf("?");
	if (index !== -1) {
		array = {};
		sUrl = sUrl.substring(index + 1);
		var sValue = sUrl.split("&");
		for (var i = 0; i < sValue.length; i++) {
			var par = sValue[i].split("=");
			array[par[0]] = par[1];
			
		}
	}
	return array;
};

GODSON_OF_SINA.prototype.upload = function (weibo, pic, reset, ErrorReset) {
	var that = this;
	if (typeof pic != "blob") {
		pic = {
			file : pic,
			keyname : "pic"
		};
	}
	var update_api = APIV.statuses.upload;
	
	var auth_args = {
		data : {
			"status" : weibo,
			"access_token" : that.sinaAdpt.getAccessToken()
		},
		headers : {},
		type : "post"
	}
	var boundary = '----multipartformboundary' + (new Date).getTime();
	var dashdash = '--';
	var crlf = '\r\n';
	var builder = '';
	builder += dashdash;
	builder += boundary;
	builder += crlf;
	
	for (var key in auth_args.data) {
		builder += 'Content-Disposition: form-data; name="' + key + '"';
		builder += crlf;
		builder += crlf;
		builder += auth_args.data[key];
		builder += crlf;
		builder += dashdash;
		builder += boundary;
		builder += crlf;
	}
	builder += 'Content-Disposition: form-data; name="' + pic.keyname + '"';
	if (pic.file.fileName) {
		builder += '; filename="' + percentEncode(pic.file.fileName) + '"';
	} else {
		builder += '; filename="' + percentEncode("godsonshare") + '"';
	}
	builder += crlf;
	if (pic.file.fileType || pic.file.type) {
		builder += 'Content-Type: ' + (pic.file.fileType || pic.file.type);
	} else {
		builder += 'Content-Type: image/png';
	}
	builder += crlf;
	builder += crlf;
	var bb = [];
	bb.push(builder);
	bb.push(pic.file);
	builder = crlf;
	builder += dashdash;
	builder += boundary;
	builder += dashdash;
	builder += crlf;
	bb.push(builder);
	
	$.ajax({
		url : update_api,
		data : new Blob(bb),
		dataType : "json",
		type : "POST",
		cache : false,
		dataType : 'text',
		processData : false,
		contentType : "multipart/form-data; boundary=" + boundary,
		success : function (data) {
			that.showMsgNotification("发送成功！");
			reset.call();
		},
		error : function () {
			that.showMsgNotification("操作失败！请重试！");
			ErrorReset.call();
		}
	});
	
	function percentEncode(s) {
		if (s == null) {
			return "";
		}
		if (s instanceof Array) {
			var e = "";
			for (var i = 0; i < s.length; ++s) {
				if (e != "")
					e += '&';
				e += percentEncode(s[i]);
			}
			return e;
		}
		s = encodeURIComponent(s);
		s = s.replace(/\!/g, "%21");
		s = s.replace(/\*/g, "%2A");
		s = s.replace(/\'/g, "%27");
		// s = s.replace("(", "%28", "g");
		s = s.replace(/\(/g, "%28");
		s = s.replace(/\)/g, "%29");
		return s;
	}
};

GODSON_OF_SINA.prototype.send_status = function (status, reset, ErrorReset) {
	var that = this;
	if (that.send)
		return;
	if (that.tolong) {
		that.createImg(status, reset, ErrorReset);
		return;
	}
	
	that.send = true;
	if (that.file) {
		that.upload(status, that.file, reset, ErrorReset);
	} else if (that.img) {
		that.post(APIV.statuses.upload_url_text, {
			status : status,
			url : that.img
		}, function (rsp) {
			that.showMsgNotification("发送成功！");
			reset.call();
		}, ErrorReset);
	} else {
		that.post(APIV.statuses.update, {
			status : status
		}, function (rsp) {
			that.showMsgNotification("发送成功！");
			reset.call();
		}, ErrorReset);
	}
};

GODSON_OF_SINA.prototype.createImg = function (status, reset, ErrorReset) {
	var that = this;
	var screenname = that.get('screenname');
	var data = makeImage(status, that);
	that.file = _dataUrlToBlob(data);
	that.fileData = data;
	status = status.substring(0, 130) + "……";
	that.tolong = false;
	that.send_status(status, reset, ErrorReset);
	
	/**
	 * 将dataUrl转化成Blob对象
	 *
	 * @param {String} dataurl
	 * @return {Blob}
	 * @api public
	 */
	function _dataUrlToBlob(dataurl) {
		return dataURLtoBlob(dataurl);
	}
};

GODSON_OF_SINA.prototype.replaceAll = function (str, data, emotions) {
	for (var key in data) {
		var value = data[key];
		if (value == null)
			value = "&nbsp;";
		if (emotions) {
			str = str.replace(new RegExp(key, "gm"), value);
		} else {
			str = str.replace(new RegExp("{{" + key + "}}", "gm"), value);
		}
	}
	return str;
};

function str_replace(search, replace, subject, count) {
	var i = 0,
	j = 0,
	temp = '',
	repl = '',
	sl = 0,
	fl = 0,
	f = [].concat(search),
	r = [].concat(replace),
	s = subject,
	ra = r instanceof Array,
	sa = s instanceof Array;
	s = [].concat(s);
	if (count) {
		this.window[count] = 0;
	}
	for (i = 0, sl = s.length; i < sl; i++) {
		if (s[i] === '') {
			continue;
		}
		for (j = 0, fl = f.length; j < fl; j++) {
			temp = s[i] + '';
			repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
			s[i] = (temp).split(f[j]).join(repl);
			if (count && s[i] !== temp) {
				this.window[count] += (temp.length - s[i].length) / f[j].length;
			}
		}
	}
	return sa ? s : s[0];
}

/**
 * 退出
 */
GODSON_OF_SINA.prototype.logout = function () {
	var that = this;
	if (that.sinaAdpt.getAccessToken()) {
		that.sinaAdpt.clearAccessToken();
		if (that.interval) {
			clearInterval(that.interval);
		}
	}
};

SINA = new GODSON_OF_SINA();

if (!SINA.get('GodSon')) {
	localStorage.clear();
	SINA.set('GodSon', true);
	SINA.set('long_flag', false);
	SINA.set('friends', "");
	SINA.set('friends_count', 0);
	SINA.set('showRightMenu', true);
	SINA.set("version", SINA.version);
}

if (!SINA.get("longSetting")) {
	chrome.tabs.create({
		url : "setting.html",
		selected : true
	});
} else {
	var longSetting = JSON.parse(SINA.get("longSetting"));
	SINA.query_time = longSetting.timer * 60 * 1000;
	if (SINA.get("version") != SINA.version) {
		SINA.set("version", SINA.version);
		chrome.tabs.create({
			url : "update.html",
			selected : true
		});
	}
}

if (SINA.sinaAdpt.getAccessToken()) {
	if (SINA.sinaAdpt.isAccessTokenExpired()) {
		SINA.sinaAdpt.clear("accessToken");
		SINA.sinaAdpt.authorize(SINA.initCallBack);
	} else {
		SINA.sinaAdpt.clear("hold_tip");
		SINA.checkUpdates();
		SINA.interval = setInterval(SINA.checkUpdates, SINA.query_time);
		SINA.getFrendCount();
	}
} else if (SINA.get("uid")) {
	SINA.sinaAdpt.authorize(SINA.initCallBack);
}

chrome.runtime.onMessage.addListener(
	function (request, sender, sendResponse) {
	if (request.greeting == "oauth_page") {
		open_page(request.filename, request.querystring)
	}
	
});

function open_page(filename, querystring) {
	
	var pageUrl = chrome.extension.getURL(filename) + querystring;
	
	chrome.tabs.create({
		'url' : pageUrl
	}, function (tab) {
		// Tab opened.
	});
}
